package com.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 功能:
 * Version: 1.0
 * Author: DR.YangLong
 * Date: 2014/7/20
 * Time: 12:31
 * Email:410357434@163.com
 * Editor:
 */
public class MyCredentialsMatcher extends SimpleCredentialsMatcher {
    /*private Cache<String, AtomicInteger> passwordRetryCache;

    public MyCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }*/

    public MyCredentialsMatcher() {
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String)token.getPrincipal();
        //retry count + 1

        /*AtomicInteger retryCount = (AtomicInteger)passwordRetryCache.get(username);
        if(retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }
        if(retryCount.incrementAndGet() > 5) {
            //if retry count > 5 throw
            throw new ExcessiveAttemptsException();
        }*/

        boolean matches =false;
        //匹配
        UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken)token;
        Object tokenCredentials = String.valueOf(usernamePasswordToken.getPassword());
        Object accountCredentials = getCredentials(info);
        matches=equals(tokenCredentials,accountCredentials);
        /*if(matches) {
            //clear retry count
            passwordRetryCache.remove(username);
        }*/
        return matches;
    }
}
